<template>
	<view class="cell">
		<!-- 模板中使用 -->
		<view>
			<drag-button :isDock="true" :existTabBar="true" @btnClick="addComponent" />
		</view>
		<view>
			<drag-button1 :isDock="true" :existTabBar="true" @btnClick="addComponent1" />
		</view>
		<!-- <xdrag @click="addComponent" ></xdrag> -->
		<!-- <button @click="addComponent">新增物料上报</button> -->
		<view v-for="(component, index2) in components" :key="index2" style="margin-left: 5px;">
			<view class="uni-list-cell" style="margin-top: 5%;">
				<view class="uni-list-cell-db">
					<text style="line-height: 100rpx;color: black;">选择上报类型:</text>
					<picker
						style="line-height: 100rpx;color: #BEBEBE;font-size: 32rpx; padding-left: 250px;margin-top: -50px;padding-top: -100px;"
						@change="pick($event,index2)" mode='selector' :value="components[index2].index"
						:range="components[index2].array" class='listPicker'>
						<!-- <view>{{ components[index2].array[components[index2].index] }}</view> -->
						<view v-if="components[index2].dianji == false" style="color: green;">
							{{ components[index2].array[components[index2].index] }}
						</view>
						<view v-if="components[index2].dianji == true" style="color: red;">
							{{ components[index2].array[components[index2].index] }}
						</view>
					</picker>
				</view>
			</view>
			<view style="margin-top: 20px;">
				<view>
					<view>品名：</view>
					<view>
						<input type="text" maxlength="20" placeholder="请输入品名" style="border: 1px solid rgba(0, 0, 0, 0.1);
		  								width: 200px;
		  								margin-top: -20px;
		  								margin-left: 50px;" @blur="inputProductName($event,index2)" />
					</view>
				</view>
			</view>
			<view style="margin-top: 20px;" v-if="components[index2].Hidden == true">
				<view>
					<view>数量：</view>
					<view>
						<input type="number" maxlength="20" placeholder="请输入数量" style="border: 1px solid rgba(0, 0, 0, 0.1);
											width: 200px;
											margin-top: -20px;
											margin-left: 50px;" @blur="inputNum($event,index2)" />
					</view>
				</view>
			</view>
			<view style="margin-top: 20px;" v-if="components[index2].Hidden == false">
				<view>
					<view>规格型号：</view>
					<view>
						<input type="text" maxlength="20" placeholder="请输入规格型号" style="border: 1px solid rgba(0, 0, 0, 0.1);
											width: 200px;
											margin-top: -20px;
											margin-left: 80px;" @blur="inputModel($event,index2)" />
					</view>
				</view>
			</view>
			<view class="cell-left" style="margin-top: 20px;">
				<view class="cell-text">申请理由：</view>
			</view>
			<view class="cell-left">
				<view class="cell-text">
					<Textarea v-model="contentText" @blur="inputContentText($event,index2)" ref="content"
						style="border: 1px solid #ccc;" pl="请在此处输入申请理由" :len='200'>
				</Textarea>
				</view>
			</view>
			<view style="margin-top: 20px;" v-if="components[index2].Hidden">
				<view>
					<view>金额：</view>
					<view>
						<input type="number" maxlength="20" placeholder="请输入金额" style="border: 1px solid rgba(0, 0, 0, 0.1);
								width: 200px;
								margin-top: -20px;
								margin-left: 50px;" @blur="input($event,index2)" />
					</view>
				</view>
			</view>
		</view>
		<view class="content">
			<!--组件位置-->
			<mianBan :list='list' @upload="upload"></mianBan>
		</view>
		<view class="button"><button @click="onsubmit">提交</button></view>
	</view>
</template>

<script>
	// 导入并注册
	import dragButton from "@/components/drag-button/drag-button.vue";
	import dragButton1 from "@/components/drag-button/drag-button1.vue";
	import mianBan from '@/components/mianBan.vue';
	import amap from '@/static/js/amap-wx.130.js';
	export default {
		data() {
			return {
				ama: [],
				materialcodeList: [],
				item: null,
				amapPlugin: null,
				gaodekey: 'a65ca3f7e4c4cf0f17d64768ce74a85e', //高德key,此处的key需要去高德平台申请获取，此key是假的！！！
				address: "", // 已经获取到的位置
				components: [],
				workOrderNumber: '',
				materialName: '',
				materialModel: '',
				materialPrice: '',
				approvalStatus: '完成',
				approvalStatus1: '完成',
				approvalStatus2: '未完成',
				date: new Date().toISOString(),
				list: [{
					name: '审批未通过',
					ishow: false,
					list: [],
				}]
			}
		},

		components: {
			mianBan,
			dragButton,
			dragButton1
		},
		mounted() {
			let _this = this;
			setInterval(function() {
				_this.date = Date.parse(new Date());
			}, 1000);
		},
		onLoad(option) {
			// console.log("进来了")
			this.item = JSON.parse(option.item)
			// this.getLocation()
			// console.log(this.item)
			uni.request({
				url: "https://www.smacaftersales.com:443/material/material/getMaterialCode",
				method: "POST",
				data: {
					productiongroup: this.item.productiongroup,
					productionleader: this.item.productionleader,
					groupLeader: this.item.groupLeader,
				},
				header: {
					// "Content-type": "application/x-www-form-urlencoded",
					"Content-type": "application/json",
					// "Content-type": "multipart/form-data"
					// "Content-type": "text/xml"
				},
				success: (res) => {
					this.item.department = res.data.data[0]
					this.item.technology = res.data.data[1]
					this.item.procure = res.data.data[2]
					this.list[0].list.push({
						time: this.dateFormat1(this.date),
						name1: "发起人",
						main: this.item.dispatchedPersonnel,
						succes: false
					})
					this.list[0].list.push({
						time: this.dateFormat1(this.date),
						name1: "审批人员",
						main: res.data.data[0] + "," + res.data.data[1] + "," + res.data.data[2],
						succes: false
					})
					this.list[0].list.push({
						time: this.dateFormat1(this.date),
						name1: "审批待审批人员",
						main: "",
						succes: false
					})
					this.list[0].list.push({
						time: this.dateFormat1(this.date),
						name1: "审批通过人员",
						main: "",
						succes: false
					})
					this.list[0].list.push({
						time: this.dateFormat1(this.date),
						name1: "审批已驳回人员",
						main: "",
						succes: false
					})
					// console.log(this.list[0].list)


				},
			})
		},

		methods: {

			//获取当前时间
			dateFormat(time) {
				let date = new Date(time);
				let year = date.getFullYear();
				// 在日期格式中，月份是从0开始的，因此要加0，使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
				let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
				let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
				let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
				let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
				let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				// 拼接
				return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
				// return year + "-" + month + "-" + day;
			},
			dateFormat1(time) {
				let date = new Date(time);
				let year = date.getFullYear();
				// 在日期格式中，月份是从0开始的，因此要加0，使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
				let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
				let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
				let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
				let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
				let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				// 拼接
				return year + "-" + month + "-" + day + " " + hours + ":" + minutes;
				// return year + "-" + month + "-" + day;
			},
			upload(item, i) {
				/* 打开一个关闭另外一个
				这里逻辑如果不同请自行修改 */
				this.list.forEach((val, index) => {
					if (i == index) {
						val.ishow = true
					} else {
						val.ishow = false
					}
				})
			},
			//获取坐标
			getLocation() {
				const _this = this;
				this.amapPlugin = new amap.AMapWX({
					key: this.gaodekey
				});
				uni.showLoading({
					title: '获取信息中'
				});
				// 成功获取位置
				_this.amapPlugin.getRegeo({
					success: (data) => {
						// console.log(data, '当前定位');

						_this.address =
							`${data[0].regeocodeData.addressComponent.city}${data[0].regeocodeData.addressComponent.district}`;

						// _this.address 可根据自己的实际情况修改
						_this.address = `${data[0].regeocodeData.formatted_address}`;
						// 传出
						_this.$emit("lodAddress", _this.address)
						uni.hideLoading();
						this.ama = data
					},
					// 获取位置失败
					fail: (err) => {
						uni.showToast({
							title: "获取位置失败，请重启小程序",
							icon: "error"
						})
					}
				});
			},
			//输入框赋值
			input(e, index) {
				this.components[index].price = e.target.value;
			},
			//下拉框赋值
			pick(e, index) {
				// console.log(index + "--------------")
				this.components[index].dianji = false
				this.components[index].index = e.target.value;
				if (e.target.value == 0) {
					this.components[index].Hidden = true;
				} else {
					this.components[index].Hidden = false;
				}
			},
			pick1(e, index) {
				this.components[index].index1 = e.target.value;
			},
			selectChange(event, index) {
				// 下拉框选项改变时更新数据
				// console.log("没进来吗")
				// console.log(this.components[0].options)
				this.components[index].options.value = event.detail.value;
			},
			//输入框赋值
			inputProductName(event, index) {
				this.components[index].productName = event.detail.value;
				// console.log(event.detail.value)
			},
			//数量赋值
			inputNum(event, index) {
				this.components[index].materialNumber = event.detail.value;
			},
			//规格型号赋值
			inputModel(event, index) {
				this.components[index].model = event.detail.value;
				// console.log(event.detail.value)
			},
			//描述赋值
			inputContentText(event, index) {
				this.components[index].contentText = event.detail.value;
			},
			addComponent() {
				this.components.push({
					contentText: '',
					model: '',
					productName: '',
					price: 0,
					imageData: '',
					selectedOption: '',
					array: ['本地采购', '公司寄件'],
					index: 0,
					matchMedia: '',
					Hidden: true,
					name: '',
					dianji: true,
					materialNumber: '',
				});

			},
			onReady() {
				this.components.push({
					contentText: '',
					model: '',
					productName: '',
					price: 0,
					imageData: '',
					selectedOption: '',
					array: ['本地采购', '公司寄件'],
					name: '',
					index: 0,
					matchMedia: '',
					Hidden: true,
					dianji: true,
					materialNumber: '',
				});
				uni.$on('examineAndApproveMsg', (data) => {
					//我把传过来的数据存到了 data 中
					this.workOrderNumber = data
					//          console.log('接收数据-----------',data);
					// console.log('examineAndApproveMsg',this.workOrderNumber);
				})
				uni.$emit('send')
				if (this.approvalStatus == '未完成') {
					// console.log()
				}
			},
			onsubmit() {
				//判断是否为空
				for (var i = 0; i < this.components.length; i++) {
					if (this.components[i].array[this.components[i].index] == "本地采购") {
						if (this.components[i].productName.length == 0) {
							uni.showToast({
								icon: 'none',
								title: '品名不能为空'
							})
							return;
						}
						if (this.components[i].materialNumber.length == 0) {
							uni.showToast({
								icon: 'none',
								title: '数量不能为空'
							})
							return;
						}
						if (this.components[i].price.length == 0) {
							uni.showToast({
								icon: 'none',
								title: '金额不能为空'
							})
							return;
						}
					}
					if (this.components[i].array[this.components[i].index] == "公司寄件") {
						if (this.components[i].productName.length == 0) {
							uni.showToast({
								icon: 'none',
								title: '品名不能为空'
							})
							return;
						}
						if (this.components[i].model.length == 0) {
							uni.showToast({
								icon: 'none',
								title: '规格型号不能为空'
							})
							return;
						}
					}
					if (this.components[i].contentText.length == 0) {
						uni.showToast({
							icon: 'none',
							title: '申请理由不能为空'
						})
						return;
					}

				}

				// console.log(this.components)
				for (var i = 0; i < this.components.length; i++) {
					uni.request({
						url: "https://www.smacaftersales.com:443/afterSalesPurchasingMaterials/afterSalesPurchasingMaterials/getApprove",
						method: "POST",
						data: {
							workordernumber: this.item.workordernumber,
							materialname: this.components[i].productName,
							materialmodel: this.components[i].model,
							materialprice: this.components[i].price,
							applicationtime: this.dateFormat(this.date),
							materialnumber: this.components[i].materialNumber,
							applicant: this.item.userId,
							pickingtype: this.components[i].array[this.components[i].index],
							pickingreason: this.components[i].contentText,
							pickingstatus: "",
							departmentapproval: '',
							technologyapproval: '',
							procureapproval: '',
						},
						header: {
							// "Content-type": "application/x-www-form-urlencoded",
							"Content-type": "application/json",
							// "Content-type": "multipart/form-data"
							// "Content-type": "text/xml"
						},
						success: (res) => {
							// console.log(res.data.data)
							if (res.data.data == 1) {
								uni.showToast({
									title: "物料上报成功",
									duration: 2000,
									icon: 'success'
								})
								this.timer = setTimeout(() => {
									uni.navigateBack({
										delta: 1
									});
								}, 2000)
							} else {
								uni.showToast({
									title: '出现错误，请重新上传',
									icon: 'error',
									duration: 2000
								})
							}
						},
					})
				}
				// 坐标获取
				// this.amapPlugin = new amap.AMapWX({
				// 	key: this.gaodekey
				// });
				// this.getLocation();
				// console.log(this.dateFormat(this.date))
				// uni.navigateBack({
				//     delta: 1
				// });
			},

			//跳转审批历史记录页面
			addComponent1() {
				// console.log(this.item)
				uni.navigateTo({
					url: `/pages/afterSaleVue/approveHistoryList/approveHistoryList?item=${JSON.stringify(this.item)}`
				});
			}

		}
	}
</script>

<style lang="less">
	page {
		background-color: #F8F8F8;
	}

	.button {
		margin-top: 120rpx;

		button {
			background-color: #11c53e;
			width: 90%;
			height: 85rpx;
			text-align: center;
			line-height: 85rpx;
			color: #fff;
		}
	}

	.color1 {
		color: #55ff7f;
	}

	.color2 {
		color: red;
	}
</style>